﻿#region ... Copyright Notice ...
/*
   Copyright 2008 Tyler Jensen

	Author: Tyler Jensen    http://www.tsjensen.com/blog

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Atrax.Contracts;
using Atrax.Library;
using Atrax.Configuration;

namespace Atrax.Master
{
	public static class ProcessorFactory
	{
		static QueryProcessorConfigurationSection m_config = null;

		public static IQueryProcessor Create(string queryType)
		{
            if (m_config == null || m_config.QueryProcessors[queryType] == null)
			{
				m_config = (QueryProcessorConfigurationSection)(System.Configuration.ConfigurationManager.GetSection("queryProcessors"));
			}

			var cfg = m_config.QueryProcessors[queryType];
            if (cfg != null)
            {
                //queryType will have something like seo.contentanalysis
                //get queryprocessor from config and then split type into type,assembly
                string[] pair = cfg.TypeName.Split(',');
                if (pair.Length != 2) return null;
                string type = pair[0].Trim();
                string assembly = pair[1].Trim();
                return CreateFromTypeName(type, assembly);
            }
            else
                return null;
		}

		static Dictionary<string, Assembly> loadedAssemblies = new Dictionary<string, Assembly>();
		static IQueryProcessor CreateFromTypeName(string type, string assembly)
		{
			if (!loadedAssemblies.ContainsKey(assembly))
			{
				LoadAssembly(assembly);
			}

			try
			{
				IQueryProcessor qp = (IQueryProcessor)loadedAssemblies[assembly].CreateInstance(type);
				return qp;
			}
			catch(Exception e)
			{
                System.Diagnostics.Debug.Write(e.ToString());
			}
			return null;
		}

		private static void LoadAssembly(string assembly)
		{
			try
			{
				Assembly asm = Assembly.Load(new AssemblyName(assembly));
				loadedAssemblies.Add(assembly, asm);
			}
            catch (Exception e)
            {
                System.Diagnostics.Debug.Write(e.ToString());
            }
        }
	}
}
